<template>
  <div class="com-web-tool-num-conversion">
    <br />
    <a-card title="数值转换">
      <a-button
        v-for="(item, index) in typeObjs"
        :key="item.label"
        class="btn"
        type="primary"
        size="small"
        @click="showClick(index)"
      >
        {{ item.label }}
      </a-button>
    </a-card>
    <w-modal
      ref="WModal"
      :title="typeObjs[type].title"
      :ok-text="result ? '清除' : '转换'"
      :ok-type="result ? 'error' : 'primary'"
      @ok="okClick"
    >
      <Form ref="formValidate" :label-width="80">
        <a-form-item label="初始数据">
          <a-input
            v-model.trim="inputText"
            :placeholder="typeObjs[type].placeholder"
          />
        </a-form-item>
        <a-form-item label="转换类型">
          <a-radio-group :options="typeObjs" v-model="conversionKey" @change="conversionChange" />
        </a-form-item>
        <a-form-item v-if="result" label="转换结果" :text="result">
          <w-copy-text :text="result">{{ result }}</w-copy-text>
        </a-form-item>
      </Form>
    </w-modal>
  </div>
</template>

<script>
import WModal from '@/components/global/modal'
export default {
  name: 'WebToolNumConversion',
  components: {
    WModal
  },
  data () {
    return {
      // 当前的类型
      type: 0,
      // 类型对象
      typeObjs: [
        {
          value: 2,
          label: '二进制',
          placeholder: '请输入（不带【0b/0B】）',
          conversionDef: 10,
          regular: /^[01]+$/
        },
        {
          value: 8,
          label: '八进制',
          placeholder: '请输入',
          conversionDef: 10,
          regular: /^[012345678]+$/
        },
        {
          value: 10,
          label: '十进制',
          placeholder: '请输入',
          conversionDef: 16,
          regular: /^[0123456789]+$/
        },
        {
          value: 16,
          placeholder: '请输入（不带）',
          label: '十六进制',
          conversionDef: 10,
          regular: /^[0123456789abcdefABCDEFxX]+$/
        }
      ],
      // 输入的数据
      inputText: '',
      // 转换的key
      conversionKey: '',
      // 转换结果
      result: ''
    }
  },
  methods: {
    showClick (index) {
      this.$refs.WModal.show()
      this.type = index
      const typeObj = this.typeObjs[index]
      this.conversionKey = typeObj.conversionDef
      this.result = ''
      this.inputText = ''
    },
    conversionChange () {
      const { regular, key } = this.typeObjs[this.type]
      if (regular.test(this.inputText)) {
        const tenNum = parseInt(this.inputText, key)
        this.result = tenNum.toString(this.conversionKey)
      } else {
        this.$message.error(`格式错误【${regular}】`)
      }
    },
    okClick () {
      if (this.result) {
        this.result = ''
        this.inputText = ''
      } else {
        if (!this.inputText) {
          this.$message.error('请输入')
          return
        }
        this.conversionChange()
      }
    }
  }
}
</script>

<style scoped></style>
